<?php
/**
 * Abstract model class.
 *
 * @category Zend
 * @package User
 * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc.
 * @version $Id$
 * @link http://framework.zend.com
 * @since Available since release 1.0
 */

abstract class Disputeo_Model_Abstract
{
    /**
     * @var Zend_Db_Table_Abstract
     */
    protected $_table;
    
    /**
     * @var type Zend_Db_Table_Row_Abstract
     */
    protected $_row;
    
    /**
     * Magic method for getting row property
     * 
     * @param string $name
     * @return string
     * @throws Exception 
     */
    public function __get($name)
    {   
        $property = '_' . $name;
        if (property_exists($this, $property)) {
            return $this->$property;
        }
        
        if ($this->_row->$name) {
            return $this->_row->$name;
        }
        
        throw new Exception('Invalid property: ' . $name);
    }
    
    /**
     * Get array of table columns
     * 
     * @return Array
     */
    public function getCols()
    {
        return $this->_table->info(Zend_Db_Table_Abstract::COLS);
    }
    
    /**
     * Set the table object
     * 
     * @param Zend_Db_Table_Abstract $table 
     */
    public function setTable(Zend_Db_Table_Abstract $table)
    {
        $this->_table = $table;
        $this->setRow($this->_table->fetchNew());
    }
    
    /**
     * Get table object
     * 
     * @return Zend_Db_Table_Abstract
     */
    public function getTable()
    {
        return $this->_table;
    }
    
    /**
     * Set table row object
     * 
     * @param Zend_Db_Table_Row_Abstract $row
     */
    public function setRow(Zend_Db_Table_Row_Abstract $row)
    {
        $this->_row = $row;
    }
    
    /**
     * @return Zend_Db_Table_Row_Abstract $row
     */
    public function getRow()
    {
        return $this->_row;
    }
    
    /**
     * Set row attributes
     * 
     * @param Array $data
     */
    public function setAttributes($data)
    {
        if (! is_array($data)) {
            return;
        }
        
        foreach ($data as $attribute => $value) {
            $property = '_' . $attribute;
            if (property_exists($this, $property)) {
                $this->$property = $value;
            } elseif (in_array($attribute, $this->getCols())) {
                $this->_row->$attribute = $value;
            }
        }
    }
    
    /**
     * Retrieve an entity
     * 
     * @param integer $id
     * @return Disputeo_Model_Abstract
     */
    protected function _find($id)
    {
        if (($set = $this->_table->find($id))) {
            $this->_row = $set->current();
        }
        return $this;
    }
    
    /**
     * Get select object
     * 
     * @return Zend_Db_Table_Select
     */
    public function query()
    {
        $select = $this->_table->select();
        $select->setIntegrityCheck(false);
        
        return $select;
    }
}

